<template>
  <div class="main-container">
    <global />
    <div class="main-content">
      <!-- 统计卡片区域 -->
      <div class="stats-container">
        <div class="stat-card">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <div class="stat-number">{{ assessmentStats.total }}</div>
            <div class="stat-label">评估总数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">📈</div>
          <div class="stat-content">
            <div class="stat-number">{{ assessmentStats.averageScore.toFixed(1) }}</div>
            <div class="stat-label">平均分数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">🎯</div>
          <div class="stat-content">
            <div class="stat-number">{{ assessmentStats.warningCount }}</div>
            <div class="stat-label">预警数量</div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 趋势图 -->
        <div class="chart-wrapper">
          <div 
            id="trendChart" 
            class="chart" 
            style="width: 100%; height: 400px;"
          ></div>
        </div>
        
        <!-- 等级分布直方图 -->
        <div class="chart-wrapper">
          <div 
            id="levelChart" 
            class="chart" 
            style="width: 100%; height: 400px;"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import axios from '../router/axios';

// 响应式数据
const chartData = ref({
  scoreRanges: ['1-2分', '3-4分', '5-6分', '7-8分', '9-10分'],
  counts: [0, 0, 0, 0, 0]
});

const assessmentStats = ref({
  total: 0,
  averageScore: 0,
  warningCount: 0
});

const levelData = ref({
  levels: ['正常', '良好', '关注', '预警'],
  counts: [0, 0, 0, 0]
});

// 获取评估统计数据
const fetchAssessmentStats = async () => {
  try {
    const response = await axios.get('api/teacher/assess/assessPage', {
      params: {
        page: 1,
        pageSize: 1000 // 获取所有数据用于统计
      }
    });
    
    const result = response.data;
    if (result.code === 1) {
      const records = result.data.records || [];
      
      // 计算统计数据
      assessmentStats.value.total = records.length;
      
      if (records.length > 0) {
        const totalScore = records.reduce((sum, record) => sum + (record.tsScore || 0), 0);
        assessmentStats.value.averageScore = totalScore / records.length;
        
        // 计算预警数量（等级为4的数量）
        assessmentStats.value.warningCount = records.filter(record => record.tsLevel === 4).length;
        
        // 计算等级分布
        const levelCounts = [0, 0, 0, 0];
        records.forEach(record => {
          const level = record.tsLevel || 1;
          if (level >= 1 && level <= 4) {
            levelCounts[level - 1]++;
          }
        });
        levelData.value.counts = levelCounts;
        
        // 计算分数段分布
        const scoreRangeCounts = [0, 0, 0, 0, 0];
        records.forEach(record => {
          const score = record.tsScore || 0;
          if (score >= 1 && score <= 2) {
            scoreRangeCounts[0]++;
          } else if (score >= 3 && score <= 4) {
            scoreRangeCounts[1]++;
          } else if (score >= 5 && score <= 6) {
            scoreRangeCounts[2]++;
          } else if (score >= 7 && score <= 8) {
            scoreRangeCounts[3]++;
          } else if (score >= 9 && score <= 10) {
            scoreRangeCounts[4]++;
          }
        });
        chartData.value.counts = scoreRangeCounts;
      }
    }
  } catch (error) {
    console.error('获取评估统计数据出错:', error);
  }
};

// 获取趋势数据（已废弃，现在直接从评估统计数据中计算）
const fetchTrendData = async () => {
  // 趋势数据现在直接从评估统计数据中计算，不再需要单独的API调用
  console.log('趋势数据已从评估统计数据中计算');
};

// 初始化趋势图
const initTrendChart = () => {
  const chart = echarts.init(document.getElementById('trendChart'));
  
  const option = {
    title: {
      text: '评估分数段分布',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const data = params[0];
        return `${data.name}<br/>学生数量: ${data.value}人`;
      }
    },
    xAxis: {
      type: 'category',
      data: chartData.value.scoreRanges,
      axisLabel: {
        color: '#222',
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#222'
      },
      name: '学生数量',
      nameTextStyle: {
        color: '#222'
      }
    },
    series: [{
      name: '学生数量',
      data: chartData.value.counts,
      type: 'bar',
      itemStyle: {
        color: function(params) {
          const colors = ['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399'];
          return colors[params.dataIndex];
        }
      },
      label: {
        show: true,
        position: 'top',
        color: '#333',
        formatter: '{c}人'
      },
      barWidth: '60%'
    }]
  };
  
  chart.setOption(option);
  
  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

// 初始化等级分布直方图
const initLevelChart = () => {
  const chart = echarts.init(document.getElementById('levelChart'));
  
  const option = {
    title: {
      text: '评估等级分布',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: levelData.value.levels,
      axisLabel: {
        color: '#222'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#222'
      }
    },
    series: [{
      name: '学生数量',
      data: levelData.value.counts,
      type: 'bar',
      itemStyle: {
        color: function(params) {
          const colors = ['#67C23A', '#409EFF', '#E6A23C', '#F56C6C'];
          return colors[params.dataIndex];
        }
      },
      label: {
        show: true,
        position: 'top',
        color: '#333'
      }
    }]
  };
  
  chart.setOption(option);
  
  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

onMounted(async () => {
  // 先获取统计数据，再获取趋势数据，最后初始化图表
  await fetchAssessmentStats();
  await fetchTrendData();
  
  // 初始化图表
  initTrendChart();
  initLevelChart();
});
</script>

<style scoped>
.main-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
}

.main-content {
  width: 100%;
  height: 100%;
  overflow: auto;
  margin-left: 220px;
  margin-top: 60px;
  width: calc(100% - 220px);
  height: calc(100% - 60px);
  padding: 20px;
}

/* 统计卡片样式 */
.stats-container {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(17, 153, 142, 0.2);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-icon {
  font-size: 32px;
  margin-right: 16px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: white;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 图表容器样式 */
.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
}

.chart-wrapper {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
  }
  
  .stat-card {
    min-width: auto;
  }
}

.content-container {
  padding: 20px;
  min-height: calc(100% - 40px);
}

.icon-data {
  color: #000;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}
</style>